"""
AI提示生成路由
"""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Optional, Dict
import json
import logging
import aiohttp

logger = logging.getLogger(__name__)

router = APIRouter()

class HintGenerationRequest(BaseModel):
    """提示生成请求模型"""
    topic: str
    purpose: str
    platform: Optional[str] = None
    model_id: Optional[str] = None  # 可选的模型ID

class BatchHintGenerationRequest(BaseModel):
    """批量提示生成请求模型"""
    topic: str
    purposes: List[str]
    platform: Optional[str] = None
    model_id: Optional[str] = None  # 可选的模型ID

class HintGenerationResponse(BaseModel):
    """提示生成响应模型"""
    hints: List[str]
    examples: List[str]
    tips: List[str]

async def call_ai_model(prompt: str, model_config: dict = None) -> str:
    """
    调用AI模型生成内容

    Args:
        prompt: 提示词
        model_config: 模型配置（如果为None，使用默认配置）

    Returns:
        生成的内容
    """
    try:
        # 如果没有提供模型配置，获取默认模型
        if not model_config:
            logger.error("❌ No AI model configured, raising error")
            raise HTTPException(status_code=503, detail="No AI model configured. Please add a model in the configuration page.")

        # 检查模型配置字段
        api_key = model_config.get("api_key")
        api_base = model_config.get("api_base")
        model_name = model_config.get("model_name")
        provider = model_config.get("provider")

        logger.debug(f"Model config: provider={provider}, model={model_name}, api_base={api_base}")

        if not api_key or not api_base:
            logger.error(f"❌ Model configuration incomplete: api_key={'exists' if api_key else 'missing'}, api_base={api_base}")
            raise HTTPException(status_code=500, detail="Model configuration incomplete: missing API key or base URL")

        # 构建API端点
        is_claude = provider in ['claude', 'anthropic']

        # 规范化api_base
        api_base = api_base.rstrip('/')
        has_v1 = api_base.endswith('/v1')

        if is_claude:
            endpoint = f"{api_base}/messages" if has_v1 else f"{api_base}/v1/messages"
        else:
            endpoint = f"{api_base}/chat/completions" if has_v1 else f"{api_base}/v1/chat/completions"

        # 构建消息
        messages = [
            {"role": "system", "content": "你是一个专业的写作助手，擅长为用户提供有针对性的写作建议和灵感启发。请以JSON格式返回结果。"},
            {"role": "user", "content": prompt}
        ]

        # 构建请求payload
        if is_claude:
            payload = {
                "model": model_name,
                "messages": messages,
                "max_tokens": 2048,
                "temperature": 0.7
            }
        else:
            payload = {
                "model": model_name,
                "messages": messages,
                "max_tokens": 2048,
                "temperature": 0.7
            }

        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }

        # 调用AI API
        logger.info(f"Calling AI API: {endpoint}")
        logger.debug(f"Headers: Authorization=Bearer ***{api_key[-4:] if len(api_key) > 4 else '***'}")

        async with aiohttp.ClientSession() as session:
            async with session.post(endpoint, headers=headers, json=payload, timeout=aiohttp.ClientTimeout(total=60)) as response:
                logger.debug(f"Response status: {response.status}")

                if response.status != 200:
                    error_text = await response.text()
                    logger.error(f"❌ AI API error {response.status}: {error_text[:500]}")
                    raise HTTPException(status_code=response.status, detail=f"AI API error: {error_text[:200]}")

                result = await response.json()
                logger.debug(f"Response keys: {list(result.keys())}")

                # 提取内容
                if is_claude:
                    content = result.get("content", [{}])[0].get("text", "")
                else:
                    content = result.get("choices", [{}])[0].get("message", {}).get("content", "")

                logger.debug(f"Extracted content length: {len(content) if content else 0}")
                return content

    except HTTPException:
        raise
    except aiohttp.ClientTimeout:
        logger.error("❌ AI model call timeout after 60 seconds")
        raise HTTPException(status_code=504, detail="AI model request timeout")
    except aiohttp.ClientError as e:
        logger.error(f"❌ AI model network error: {str(e)}")
        raise HTTPException(status_code=502, detail=f"Network error: {str(e)}")
    except Exception as e:
        logger.error(f"❌ Failed to call AI model: {type(e).__name__}: {str(e)}")
        import traceback
        logger.error(f"Traceback: {traceback.format_exc()}")
        raise HTTPException(status_code=500, detail=f"AI call failed: {str(e)}")

def build_ai_prompt(topic: str, purpose: str) -> str:
    """
    构建AI提示词

    Args:
        topic: 主题
        purpose: 目的类型

    Returns:
        AI提示词
    """
    prompt_templates = {
        "audience": f"""请为主题"{topic}"生成目标读者分析的写作建议。

请以JSON格式返回，包含以下三个部分：
1. hints：4个针对性的目标读者群体描述
2. examples：4个具体的读者画像示例
3. tips：3个选择目标读者的实用技巧

示例格式：
{{
    "hints": ["专业人士群体", "兴趣爱好者", ...],
    "examples": ["在相关领域工作的专业人士", ...],
    "tips": ["💡 考虑读者的专业背景", ...]
}}

请确保建议具有针对性和实用性，充分考虑"{topic}"这个主题的特点。""",

        "viewpoint": f"""请为主题"{topic}"生成核心观点的写作建议。

请以JSON格式返回，包含以下三个部分：
1. hints：4个有深度的观点角度
2. examples：4个具体的观点表述示例
3. tips：3个形成独特观点的技巧

示例格式：
{{
    "hints": ["从战略角度分析", "探讨深层影响", ...],
    "examples": ["这不仅是技术问题，更是...", ...],
    "tips": ["💡 结合最新发展趋势", ...]
}}

请确保观点新颖、有深度，能够激发关于"{topic}"的思考。""",

        "material": f"""请为主题"{topic}"生成素材收集的建议。

请以JSON格式返回，包含以下三个部分：
1. hints：4个重要的素材类型
2. examples：4个具体的素材来源示例
3. tips：3个收集高质量素材的技巧

示例格式：
{{
    "hints": ["行业数据报告", "典型案例", ...],
    "examples": ["权威机构发布的研究报告", ...],
    "tips": ["💡 寻找最新的数据支撑", ...]
}}

请确保素材建议实用、易获取，能够充分支撑"{topic}"的写作。""",

        "style": f"""请为主题"{topic}"生成写作风格的建议。

请以JSON格式返回，包含以下三个部分：
1. hints：4种适合的写作风格
2. examples：4个具体的风格运用示例
3. tips：3个选择合适风格的技巧

示例格式：
{{
    "hints": ["专业分析风格", "通俗科普风格", ...],
    "examples": ["使用专业术语准确描述", ...],
    "tips": ["💡 根据读者群体调整风格", ...]
}}

请确保风格建议多样化，适合不同场景下"{topic}"的表达需求。""",

        "goal": f"""请为主题"{topic}"生成写作目标的建议。

请以JSON格式返回，包含以下三个部分：
1. hints：4个明确的写作目标
2. examples：4个具体的效果期望示例
3. tips：3个设定有效目标的技巧

示例格式：
{{
    "hints": ["让读者深入理解", "激发行动意愿", ...],
    "examples": ["读者能够掌握核心概念", ...],
    "tips": ["💡 设定可衡量的目标", ...]
}}

请确保目标清晰、可达成，能够指导"{topic}"的写作方向。"""
    }

    return prompt_templates.get(purpose, prompt_templates["audience"])

def parse_ai_response_strict(content: str, topic: str, purpose: str) -> Dict:
    """
    严格解析AI响应内容，失败则抛出异常

    Args:
        content: AI生成的内容
        topic: 主题
        purpose: 目的

    Returns:
        结构化的提示数据
    """
    if not content:
        raise HTTPException(status_code=500, detail="AI returned empty content")

    try:
        # 查找JSON内容
        if '```json' in content:
            start = content.find('```json') + 7
            end = content.find('```', start)
            if end > start:
                json_str = content[start:end].strip()
                data = json.loads(json_str)
        elif '{' in content and '}' in content:
            start = content.find('{')
            end = content.rfind('}') + 1
            json_str = content[start:end]
            data = json.loads(json_str)
        else:
            # 尝试直接解析
            data = json.loads(content)

        # 验证数据结构
        if not all(key in data for key in ['hints', 'examples', 'tips']):
            logger.error(f"❌ AI response missing required fields. Got keys: {list(data.keys())}")
            raise HTTPException(status_code=500, detail=f"AI response format invalid: missing required fields")

        return {
            "hints": data.get("hints", [])[:4],  # 最多4个
            "examples": data.get("examples", [])[:4],  # 最多4个
            "tips": data.get("tips", [])[:3]  # 最多3个
        }

    except json.JSONDecodeError as e:
        logger.error(f"❌ Failed to parse AI JSON response: {str(e)}")
        logger.error(f"Content: {content[:500]}")
        raise HTTPException(status_code=500, detail=f"Failed to parse AI response as JSON: {str(e)}")
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ Unexpected error parsing AI response: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error parsing AI response: {str(e)}")

def parse_ai_response(content: str, topic: str, purpose: str) -> Dict:
    """
    解析AI响应内容

    Args:
        content: AI生成的内容
        topic: 主题
        purpose: 目的

    Returns:
        结构化的提示数据
    """
    try:
        # 尝试解析JSON
        if content:
            # 查找JSON内容
            if '```json' in content:
                start = content.find('```json') + 7
                end = content.find('```', start)
                if end > start:
                    json_str = content[start:end].strip()
                    data = json.loads(json_str)
            elif '{' in content and '}' in content:
                start = content.find('{')
                end = content.rfind('}') + 1
                json_str = content[start:end]
                data = json.loads(json_str)
            else:
                # 尝试直接解析
                data = json.loads(content)

            # 验证数据结构
            if all(key in data for key in ['hints', 'examples', 'tips']):
                return {
                    "hints": data.get("hints", [])[:4],  # 最多4个
                    "examples": data.get("examples", [])[:4],  # 最多4个
                    "tips": data.get("tips", [])[:3]  # 最多3个
                }
    except Exception as e:
        logger.warning(f"Failed to parse AI response: {str(e)}")

    # 返回降级方案
    return get_fallback_hints_data(topic, purpose)

async def generate_hints_for_topic(topic: str, purpose: str, model_config: dict = None) -> Dict:
    """
    根据主题和目的生成智能提示（使用AI模型）

    Args:
        topic: 主题
        purpose: 目的
        model_config: 模型配置

    Returns:
        提示数据
    """
    logger.debug(f"Generating hints for topic='{topic}', purpose='{purpose}'")

    # 构建AI提示词
    prompt = build_ai_prompt(topic, purpose)
    logger.debug(f"Built prompt length: {len(prompt)}")

    # 调用AI模型（会抛出异常如果失败）
    ai_response = await call_ai_model(prompt, model_config)

    if not ai_response:
        logger.error("❌ AI model returned empty response")
        raise HTTPException(status_code=500, detail="AI model returned empty response")

    logger.info(f"✅ AI model responded successfully for topic: {topic}")

    # 解析AI响应（会抛出异常如果解析失败）
    hints_data = parse_ai_response_strict(ai_response, topic, purpose)

    return hints_data

def extract_keywords(topic: str) -> List[str]:
    """
    从主题中提取关键词
    """
    import re
    # 移除常见的连接词
    topic_clean = re.sub(r'[的了在是和与及或等]', ' ', topic)
    # 分词
    words = [w for w in topic_clean.split() if len(w) >= 2]

    # 如果没有提取到词，返回原主题
    if not words:
        words = [topic]

    return words[:3]  # 返回前3个关键词

def get_fallback_hints_data(topic: str, purpose: str) -> Dict:
    """
    获取降级提示数据（当AI生成失败时）
    """
    keywords = extract_keywords(topic)
    keyword = keywords[0] if keywords else topic

    fallback_data = {
        "audience": {
            "hints": [
                f"对{keyword}感兴趣的技术专家",
                f"关注{topic}发展的行业从业者",
                f"需要了解{keyword}的决策者",
                f"研究{topic}的学者和学生"
            ],
            "examples": [
                f"在{keyword}领域工作3年以上的工程师",
                f"关注{topic}产业链的投资人",
                f"负责{keyword}相关项目的管理者",
                f"对{topic}有实际需求的企业用户"
            ],
            "tips": [
                f"💡 考虑{topic}的技术门槛和专业性",
                f"💡 分析不同群体对{keyword}的关注点",
                f"💡 思考{topic}能为读者带来什么价值"
            ]
        },
        "viewpoint": {
            "hints": [
                f"{topic}的战略意义分析",
                f"{keyword}带来的机遇与挑战",
                f"从产业链角度看{topic}",
                f"{topic}的未来发展趋势"
            ],
            "examples": [
                f"{topic}不仅是技术问题，更是战略布局",
                f"深入分析{keyword}的核心价值",
                f"{topic}将重塑行业格局",
                f"从全球视角看{topic}的重要性"
            ],
            "tips": [
                f"💡 结合{topic}的最新进展",
                f"💡 提出对{keyword}的独特见解",
                f"💡 避免陈词滥调，要有新观点"
            ]
        },
        "material": {
            "hints": [
                f"{topic}的行业数据",
                f"{keyword}的成功案例",
                f"相关政策和规划",
                f"技术发展历程"
            ],
            "examples": [
                f"某企业在{topic}领域的突破性进展",
                f"关于{keyword}的最新研究报告",
                f"{topic}相关的政策支持措施",
                f"国内外{keyword}发展对比"
            ],
            "tips": [
                f"💡 收集{topic}的权威数据",
                f"💡 寻找{keyword}的典型案例",
                f"💡 注意信息的时效性和准确性"
            ]
        },
        "style": {
            "hints": [
                f"深度分析{topic}的专业风格",
                f"通俗解释{keyword}的科普风格",
                f"案例驱动的实践风格",
                f"数据支撑的理性风格"
            ],
            "examples": [
                f"用专业术语准确描述{topic}",
                f"用生活化语言解释{keyword}",
                f"通过故事展现{topic}的价值",
                f"用数据图表呈现{keyword}现状"
            ],
            "tips": [
                f"💡 根据{topic}的复杂度选择风格",
                f"💡 考虑读者对{keyword}的了解程度",
                f"💡 保持风格与内容的一致性"
            ]
        },
        "goal": {
            "hints": [
                f"让读者理解{topic}的重要性",
                f"帮助读者掌握{keyword}知识",
                f"激发对{topic}的思考",
                f"提供实际行动指南"
            ],
            "examples": [
                f"读者能够理解{topic}的核心概念",
                f"掌握{keyword}的基本原理",
                f"获得参与{topic}的具体方法",
                f"形成对{keyword}的独立判断"
            ],
            "tips": [
                f"💡 明确{topic}的价值主张",
                f"💡 设定可达成的学习目标",
                f"💡 提供可操作的建议"
            ]
        }
    }

    return fallback_data.get(purpose, fallback_data["audience"])

def get_fallback_hints(topic: str, purpose: str) -> HintGenerationResponse:
    """
    获取降级提示（当AI生成失败时）
    """
    data = get_fallback_hints_data(topic, purpose)
    return HintGenerationResponse(**data)

@router.post("/generate-hints", response_model=HintGenerationResponse)
async def generate_hints(request: HintGenerationRequest):
    """
    生成动态提示内容
    """
    logger.info(f"🔥 Received hints request: topic='{request.topic}', purpose='{request.purpose}'")

    try:
        # 获取模型配置
        model_config = None
        if request.model_id:
            try:
                from ..core.database import get_db
                db = await get_db()
                model_config = await db.model_configs.find_one({"id": request.model_id})
            except Exception as e:
                logger.warning(f"Cannot get model config: {e}")

        # 根据主题和问题类型生成提示
        hints_data = await generate_hints_for_topic(
            topic=request.topic,
            purpose=request.purpose,
            model_config=model_config
        )

        logger.info(f"✅ Generated {len(hints_data.get('hints', []))} hints for topic: {request.topic}")
        return HintGenerationResponse(**hints_data)

    except Exception as e:
        logger.error(f"❌ Failed to generate hints: {str(e)}")
        import traceback
        logger.error(f"Traceback: {traceback.format_exc()}")
        raise

@router.options("/generate-hints")
async def options_generate_hints():
    """
    处理OPTIONS请求（CORS预检）
    """
    return {"message": "OK"}

@router.post("/generate-hints/batch", response_model=Dict[str, HintGenerationResponse])
async def generate_batch_hints(request: BatchHintGenerationRequest):
    """
    批量生成动态提示内容
    """
    logger.info(f"🔥 Received batch hints request: topic='{request.topic}', purposes={request.purposes}")

    try:
        # 获取模型配置
        model_config = None
        if request.model_id:
            try:
                from ..core.database import get_db
                db = await get_db()
                model_config = await db.model_configs.find_one({"id": request.model_id})
            except Exception as e:
                logger.warning(f"Cannot get model config: {e}")

        results = {}
        for purpose in request.purposes:
            hints_data = await generate_hints_for_topic(
                topic=request.topic,
                purpose=purpose,
                model_config=model_config
            )
            results[purpose] = HintGenerationResponse(**hints_data)

        logger.info(f"✅ Generated hints for {len(results)} purposes: {list(results.keys())}")
        return results

    except Exception as e:
        logger.error(f"❌ Failed to generate batch hints: {str(e)}")
        import traceback
        logger.error(f"Traceback: {traceback.format_exc()}")
        raise

@router.get("/available-models")
async def get_available_models():
    """
    获取可用的AI模型列表（用于头脑风暴提示生成）
    不需要认证，直接返回启用的模型
    """
    try:
        from ..core.database import get_db_direct
        db = await get_db_direct()

        # 查询所有启用的模型
        models = []
        async for model in db.model_configs.find({"enabled": True}):
            models.append({
                "id": model.get("id", str(model.get("_id", ""))),
                "name": model.get("name", "Unknown Model"),
                "provider": model.get("provider", "unknown"),
                "status": model.get("status", "unknown"),
                "model_name": model.get("model_name", ""),
                "enabled": model.get("enabled", False)
            })

        logger.info(f"✅ Returning {len(models)} available models for hints generation")
        return models

    except Exception as e:
        logger.error(f"Failed to get available models: {str(e)}")
        # 返回空列表而不是错误，让前端显示"暂无可用模型"
        return []

@router.options("/available-models")
async def options_available_models():
    """
    处理OPTIONS请求（CORS预检）
    """
    return {"message": "OK"}